<template>
  <div>
    <el-table :data="allRoles" ref="userRoleTable" tooltip-effect="dark" border style="width: 100%" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
    </el-table>
    <div class="mt_5 tac">
      <el-button type="primary" size="mini" @click="saveUserRole">确定</el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  props:['entityId'],
  data() {
    return {
      allRoles :[],
      selectRoles:[],
    }
  },
  mounted() {
    this.loadUserRole();
  },
  methods: {
    handleSelectionChange(selectRows){
      this.selectRoles = selectRows
    },
    saveUserRole(){
      let userRoles = [];
      this.selectRoles.forEach((r)=>{
        userRoles.push(r.id)
      })
      request({
        url: '/sys/useradmin/saveuserrole',
        data: {userId : this.entityId, userRoles:userRoles}
      }).then(res=>{
        if(res.code === '200'){
          this.$message.success(res.msg)
        }
      })
    },
    loadUserRole(){
      request({
        url: '/sys/useradmin/listuserrole',
        data: {userId : this.entityId}
      }).then(res => {
        const { data } = res
        this.allRoles = data.allRoles
        this.$nextTick(()=>{
          this.allRoles.forEach((item)=>{
            if(data.userRoles.filter((u)=> u.id === item.id).length > 0){
              this.$refs.userRoleTable && this.$refs.userRoleTable.toggleRowSelection(item, true)
            }
          })
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
